const fs = require('fs');
const path = require('path');
const chalk = require('chalk');

// 添加chalk依赖
try {
  require('chalk');
} catch {
  console.log('正在安装必要依赖...');
  require('child_process').execSync('npm install chalk --save-dev');
}

const requiredDirs = [
  'logs',
  'src/utils',
  'src/services',
  'src/controllers',
  'src/middleware',
  'src/routes'
];

const requiredFiles = [
  'src/utils/logger.ts',
  'src/middleware/error.ts',
  'src/middleware/rateLimiter.ts',
  '.env',
  'tsconfig.json',
  'package.json'
];

const requiredDeps = [
  'winston',
  'express',
  'mongoose',
  'node-cache',
  'zod',
  'typescript'
];

console.log(chalk.blue('🔍 开始项目环境检查...\n'));

// 检查目录
console.log(chalk.yellow('检查必要目录:'));
requiredDirs.forEach(dir => {
  const dirPath = path.join(__dirname, '..', dir);
  if (fs.existsSync(dirPath)) {
    console.log(chalk.green(`✓ ${dir} 目录存在`));
  } else {
    console.log(chalk.red(`✗ ${dir} 目录缺失`));
  }
});

console.log('\n' + chalk.yellow('检查必要文件:'));
requiredFiles.forEach(file => {
  const filePath = path.join(__dirname, '..', file);
  if (fs.existsSync(filePath)) {
    console.log(chalk.green(`✓ ${file} 文件存在`));
  } else {
    console.log(chalk.red(`✗ ${file} 文件缺失`));
  }
});

// 检查依赖
console.log('\n' + chalk.yellow('检查必要依赖:'));
const packageJson = require('../package.json');
const allDeps = { ...packageJson.dependencies, ...packageJson.devDependencies };

requiredDeps.forEach(dep => {
  if (allDeps[dep]) {
    console.log(chalk.green(`✓ ${dep} 已安装 (${allDeps[dep]})`));
  } else {
    console.log(chalk.red(`✗ ${dep} 未安装`));
  }
});

// 检查TypeScript配置
console.log('\n' + chalk.yellow('检查TypeScript配置:'));
try {
  const tsConfig = require('../tsconfig.json');
  if (tsConfig.compilerOptions.baseUrl) {
    console.log(chalk.green('✓ 路径别名配置正确'));
  } else {
    console.log(chalk.red('✗ 缺少路径别名配置'));
  }
} catch (error) {
  console.log(chalk.red('✗ 无法读取tsconfig.json'));
}

// 检查环境变量
console.log('\n' + chalk.yellow('检查环境变量:'));
try {
  const envContent = fs.readFileSync(path.join(__dirname, '..', '.env'), 'utf8');
  const requiredEnvVars = ['PORT', 'MONGODB_URI', 'JWT_SECRET'];
  const missingVars = [];

  requiredEnvVars.forEach(variable => {
    if (!envContent.includes(variable + '=')) {
      missingVars.push(variable);
    }
  });

  if (missingVars.length === 0) {
    console.log(chalk.green('✓ 所有必要的环境变量都已配置'));
  } else {
    console.log(chalk.red(`✗ 缺少环境变量: ${missingVars.join(', ')}`));
  }
} catch (error) {
  console.log(chalk.red('✗ .env文件不存在或无法读取'));
}

// 总结
console.log('\n' + chalk.blue('检查完成！'));
